/**
 * 处理用户相关的路由
 */

const { SuccessModel, ErrorModel } = require("../model/responseModel.js");

const {
  findUser,
  createUser,
} = require("../controllers/user.js");

const { decrypt } = require('../utils/encrypt')

const jwt = require('jsonwebtoken')

const handleUserRoute = (req, res) => {
  // 定义 处理路由的逻辑
  const method = req.method;

  // const id = req.query.id;
  const userBody = req.body;

  // 注册路由
  if (method === "POST" && req.path === "/api/user/register") {

    const userDataPromise = findUser(userBody.username)
    return userDataPromise.then(findData => {

      // 如果userData有数据，则用户已存在
      if(findData) {
        return new ErrorModel("用户已存在", "/api/user/register");
      }
      // userData没数据，则进入注册
      else {
        const createUserPromise = createUser(userBody)
        return createUserPromise.then(createData => {

          return new SuccessModel(createData);

        })
      }
    })
  }

  // 登录路由
  if (method === "POST" && req.path === "/api/user/login") {
    
    const userDataPromise = findUser(userBody.username)
    return userDataPromise.then(findData => {
      
      // 如果userData没数据，提示用户不存在
      if(!findData) {
        return new ErrorModel("用户不存在！", "/api/user/login");
      }
      // userData有数据，用户存在，比对密码
      else {

        // 密码解密，密码正确
        if(decrypt(findData.password) === decrypt(userBody.password)) {
          
          const objReturn = {
            userInfo: findData,     //返回userInfo
            token: jwt.sign({username: findData.username},'slowgoat')
          }
          return new SuccessModel(objReturn);

        }
        // 密码错误
        else {
          return new ErrorModel("账号或者密码错误！", "/api/user/login");
        }
      }
    })
  }

};

module.exports = handleUserRoute;